package com.cmccgz.baselibrary.view.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.cmccgz.baselibrary.R;
import com.cmccgz.baselibrary.image.GlideUtils;
import com.cmccgz.baselibrary.utils.BoxingUtils;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.baselibrary.view.MyGridView;
import com.cmccgz.baselibrary.view.photoview.ImageShowActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


public class BoxingAdapter extends BaseAdapter implements AdapterView.OnItemClickListener{
    private int gvWidth;
    private Context mContext;
    private LayoutInflater inflater;
    private boolean isEdit = false;//是否編輯模式
    private MyGridView mGridView;
    private List<String> urls;
    private int count;
    private final static int MAXSIZE=1024*1024;
    private Object link;
    /**
     * @param isEdit
     * @param gridView
     * @param urls
     * @param gvWidth
     */
    public BoxingAdapter(boolean isEdit, MyGridView gridView, List<String> urls, int gvWidth,Object link, int count) {
        this.isEdit = isEdit;
        this.mGridView = gridView;
        mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mGridView.setOnItemClickListener(this);
        mContext = mGridView.getContext();
        inflater = LayoutInflater.from(mContext);
        this.gvWidth = gvWidth;
        if (urls == null) {
            urls = new ArrayList<>();
        }
        this.urls = urls;
        this.count = count;
        this.link=link;
    }

    @Override
    public int getCount() {
        if (urls == null || urls.size() == 0) {
            return isEdit ? 1 : 0;
        }
        return isEdit ? urls.size() + 1 : urls.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        int numColumns = mGridView.getNumColumns();
        int itemWidth = gvWidth / numColumns;

        AbsListView.LayoutParams params = null;
        try {
            params = (AbsListView.LayoutParams) convertView.getLayoutParams();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (params == null) {
            params = new AbsListView.LayoutParams(itemWidth, itemWidth);
        } else {
            params.height = itemWidth;
        }

        switch (getItemViewType(position)) {
            case -1:
                //新增
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.item_photo_add, parent, false);
                    new AddViewHolder(convertView);
                }
                AddViewHolder addViewHolder = (AddViewHolder) convertView.getTag();
                addViewHolder.iv_add.setLayoutParams(params);
                break;
            case 1:
                //默认item
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.item_photo_normal, parent, false);
                    new NormalViewHolder(convertView);
                }
                NormalViewHolder normalViewHolder = (NormalViewHolder) convertView.getTag();
                final String url = urls.get(position);
                if (link instanceof Fragment) {
                    GlideUtils.loadImage((Fragment) link, url, normalViewHolder.iv_photo);
                }else{
                    GlideUtils.loadImage(mContext, url, normalViewHolder.iv_photo);
                }
                normalViewHolder.iv_delete.setVisibility(isEdit ? View.VISIBLE : View.GONE);
                normalViewHolder.itemView.setLayoutParams(params);
                normalViewHolder.iv_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        urls.remove(position);
                        notifyDataSetChanged();
                    }
                });
                break;
        }
        return convertView;
    }

    @Override
    public int getItemViewType(int position) {
        return isEdit && position == getCount() - 1 ? -1 : 1;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (getItemViewType(position)) {
            case -1:
                setOnClickSpan(view, 1000);
                if (urls.size() >= count) {
                    ToastUtils.show(mContext, "最多选择" + count + "张图片");
                    return;
                }else{
                    BoxingUtils.selectMuliImage(mContext,count-urls.size());
                  /*  String cachePath = BoxingFileHelper.getCacheDir(mContext);
                    if (TextUtils.isEmpty(cachePath)) {
                        Toast.makeText(mContext, R.string.boxing_storage_deny, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Uri destUri = new Uri.Builder()
                            .scheme("file")
                            .appendPath(cachePath)
                            .appendPath(String.format(Locale.US, "%s.png", System.currentTimeMillis()))
                            .build();
                    BoxingConfig config = new BoxingConfig(BoxingConfig.Mode.MULTI_IMG)
                            .needCamera(R.drawable.ic_boxing_camera_white)
                            .needGif()
                            .withMaxCount(count-urls.size())
                            .withCropOption(new BoxingCropOption(destUri));
                    Boxing.of(config).withIntent(mContext, BoxingActivity.class).start(((Activity) mContext), REQUEST_CODE);*/
                }
                break;
            case 1:
                Intent intent = new Intent(mContext, ImageShowActivity.class);
                intent.putExtra(ImageShowActivity.KEY_IMGE_URLS, (Serializable) urls);
                intent.putExtra(ImageShowActivity.KEY_IMGE_POSITION, position);
                mContext.startActivity(intent);
                break;
        }
    }

    private class NormalViewHolder {
        private final ImageView iv_delete;
        private final ImageView iv_photo;
        private View itemView;

        public NormalViewHolder(View itemView) {
            this.itemView = itemView;
            itemView.setTag(this);
            iv_photo = ((ImageView) itemView.findViewById(R.id.iv_photo));
            iv_delete = ((ImageView) itemView.findViewById(R.id.iv_delete));
        }
    }

    private class AddViewHolder {
        private final ImageView iv_add;
        private View itemView;

        public AddViewHolder(View itemView) {
            this.itemView = itemView;
            itemView.setTag(this);
            iv_add = ((ImageView) itemView.findViewById(R.id.iv_add));
        }
    }



    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        List<String> urlResult = BoxingUtils.getUrlResult(requestCode, resultCode, data, mContext, MAXSIZE);
        urls.addAll(urlResult);
        notifyDataSetChanged();
    }



    private void setOnClickSpan(final View view, long mis) {
        if (view==null) {
            return;
        }
        view.setEnabled(false);
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                view.setEnabled(true);
            }
        }, mis);
    }

    public List<String>getSelectUrls(){
        return urls==null?new ArrayList<String>():urls;
    }
}
